const noteUtils = window.markAnything.utils;
// 添加笔记
const addNote = async (content, fromSelection = false) => {
    try {
      await noteUtils.checkStorageAvailable();
      // 获取现有笔记
      const result = await chrome.storage.local.get(['notes']);
      const notes = result.notes || [];
      
      // 创建新笔记
      const note = {
        id: Date.now(), // 使用时间戳作为ID
        content,
        url: window.location.href,
        pageTitle: document.title,
        createdAt: new Date().toISOString(),
        selectedText: window.getSelection().toString() || ''
      };
      
      // 添加到笔记列表
      notes.push(note);
      
      // 保存更新后的笔记列表
      await chrome.storage.local.set({ notes });
      
      // 如果编辑器没有打开且不是从选择菜单添加的，则显示编辑器
      if (!document.querySelector('.todo-input-container.notes-container') && !fromSelection) {
        showNoteEditor();
      }
      
      return note.id;
    } catch (error) {
      console.error('保存笔记失败:', error);
      throw error;
    }
  };

// 获取所有笔记并按URL分组
const getAllNotes = async () => {
  try {
    await noteUtils.checkStorageAvailable();
    // 获取所有笔记
    const result = await chrome.storage.local.get(['notes']);
    const notes = result.notes || [];
    
    // 按URL分组
    const groupedNotes = notes.reduce((groups, note) => {
      if (!groups[note.url]) {
        groups[note.url] = {
          pageTitle: note.pageTitle,
          url: note.url,
          notes: []
        };
      }
      groups[note.url].notes.push(note);
      return groups;
    }, {});

    // 对每个组内的笔记按时间倒序排序
    Object.values(groupedNotes).forEach(group => {
      group.notes.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
    });

    // 将分组转换为数组并按最新笔记时间排序
    const sortedGroups = Object.values(groupedNotes).sort((a, b) => {
      return new Date(b.notes[0].createdAt) - new Date(a.notes[0].createdAt);
    });

    return sortedGroups;
  } catch (error) {
    console.error('获取笔记失败:', error);
    throw error;
  }
};

// 删除笔记
const deleteNote = async (id) => {
  try {
    await noteUtils.checkStorageAvailable();
    // 获取现有笔记
    const result = await chrome.storage.local.get(['notes']);
    let notes = result.notes || [];
    
    // 移除指定ID的笔记
    notes = notes.filter(note => note.id !== id);
    
    // 保存更新后的笔记列表
    await chrome.storage.local.set({ notes });
  } catch (error) {
    console.error('删除笔记失败:', error);
    throw error;
  }
};

// 显示笔记编辑器
const showNoteEditor = async () => {
  // 检查是否已存在编辑器
  const existingEditor = document.querySelector('.todo-input-container');
  if (existingEditor) {
    const isNoteEditor = existingEditor.querySelector('h2').textContent === '笔记';
    existingEditor.remove();
    // 如果关闭的不是笔记编辑器，则打开笔记编辑器
    if (!isNoteEditor) {
      // 添加一个小延迟，确保DOM更新完成
      setTimeout(() => {
        showNoteEditor();
      }, 50);
    }
    return;
  }

  const container = document.createElement('div');
  container.className = 'todo-input-container notes-container';

  // 阻止滚动事件传播
  container.addEventListener('wheel', (e) => {
    const target = e.target;
    let isScrollable = false;
    let element = target;
    
    while (element !== container && element !== null) {
      if (element.scrollHeight > element.clientHeight) {
        isScrollable = true;
        break;
      }
      element = element.parentElement;
    }
    
    if (isScrollable) {
      const scrollTop = element.scrollTop;
      const scrollHeight = element.scrollHeight;
      const clientHeight = element.clientHeight;
      
      if ((scrollTop === 0 && e.deltaY < 0) || 
          (scrollTop + clientHeight >= scrollHeight && e.deltaY > 0)) {
        return;
      }
      
      e.stopPropagation();
    }
  }, { passive: false });

  // 添加标题
  const header = document.createElement('div');
  header.className = 'todo-header';
  header.innerHTML = `
    <div class="todo-header-left">
      <h2>笔记</h2>
      <span class="note-page-title">${document.title}</span>
    </div>
    <button class="todo-close-button" title="关闭">×</button>
  `;
  
  // 添加关闭按钮事件监听器
  const closeButton = header.querySelector('.todo-close-button');
  closeButton.addEventListener('click', () => container.remove());
  
  // 创建内容包装器
  const contentWrapper = document.createElement('div');
  contentWrapper.className = 'notes-wrapper';
  
  // 添加输入区域
  const inputSection = document.createElement('div');
  inputSection.className = 'notes-input-section';
  
  const textarea = document.createElement('textarea');
  textarea.placeholder = '输入笔记内容...';
  textarea.className = 'notes-textarea';
  
  const buttonContainer = document.createElement('div');
  buttonContainer.className = 'notes-button-container';
  
  const saveButton = document.createElement('button');
  saveButton.textContent = '保存';
  saveButton.className = 'notes-button save';
  
  const cancelButton = document.createElement('button');
  cancelButton.textContent = '取消';
  cancelButton.className = 'notes-button cancel';
  
  buttonContainer.appendChild(saveButton);
  buttonContainer.appendChild(cancelButton);
  
  inputSection.appendChild(textarea);
  inputSection.appendChild(buttonContainer);
  
  // 添加历史记录区域
  const historySection = document.createElement('div');
  historySection.className = 'notes-history-section';
  
  const historyTitle = document.createElement('h3');
  historyTitle.textContent = '历史笔记';
  historyTitle.className = 'notes-history-title';

  // 添加搜索区域
  const searchSection = document.createElement('div');
  searchSection.className = 'notes-search-section';
  
  const searchInput = document.createElement('input');
  searchInput.type = 'text';
  searchInput.className = 'notes-search-input';
  searchInput.placeholder = '搜索历史笔记...';
  
  const clearButton = document.createElement('button');
  clearButton.className = 'notes-search-clear';
  clearButton.innerHTML = '×';
  clearButton.title = '清除搜索';
  
  searchSection.appendChild(searchInput);
  searchSection.appendChild(clearButton);
  
  // 添加搜索功能
  const handleSearch = () => {
    const searchText = searchInput.value.toLowerCase().trim();
    clearButton.classList.toggle('visible', searchText.length > 0);
    
    const noteItems = document.querySelectorAll('.notes-item');
    const noteGroups = document.querySelectorAll('.notes-group');
    
    noteItems.forEach(item => {
      const noteText = item.querySelector('.notes-item-text').textContent.toLowerCase();
      const isMatch = noteText.includes(searchText);
      item.classList.toggle('hidden', !isMatch);
    });
    
    // 隐藏空的笔记组
    noteGroups.forEach(group => {
      const visibleNotes = group.querySelectorAll('.notes-item:not(.hidden)').length;
      group.classList.toggle('empty', visibleNotes === 0);
    });
  };
  
  searchInput.addEventListener('input', handleSearch);
  clearButton.addEventListener('click', () => {
    searchInput.value = '';
    handleSearch();
    searchInput.focus();
  });
  
  const historyList = document.createElement('div');
  historyList.className = 'notes-history-list';
  
  // 加载历史记录
  try {
    const noteGroups = await getAllNotes();
    if (noteGroups.length === 0) {
      historyList.innerHTML = '<div class="notes-empty">暂无笔记</div>';
    } else {
      noteGroups.forEach(group => {
        const groupContainer = document.createElement('div');
        groupContainer.className = 'notes-group';
        
        const groupHeader = document.createElement('div');
        groupHeader.className = 'notes-group-header';
        groupHeader.innerHTML = `
          <a href="${group.url}" target="_blank" class="notes-group-title">${group.pageTitle}</a>
          <span class="notes-group-count">${group.notes.length}条笔记</span>
        `;
        
        const notesContainer = document.createElement('div');
        notesContainer.className = 'notes-group-notes';
        
        group.notes.forEach(note => {
          const item = document.createElement('div');
          item.className = 'notes-item';
          
          const content = document.createElement('div');
          content.className = 'notes-item-content';
          
          const text = document.createElement('div');
          text.className = 'notes-item-text';
          text.textContent = note.content;
          
          const meta = document.createElement('div');
          meta.className = 'notes-item-meta';
          const date = new Date(note.createdAt);
          meta.innerHTML = `<span>${date.toLocaleString()}</span>`;
          
          content.appendChild(text);
          content.appendChild(meta);
          
          const actions = document.createElement('div');
          actions.className = 'notes-item-actions';
          
          const editButton = document.createElement('button');
          editButton.className = 'notes-action-btn edit';
          editButton.innerHTML = '✎';
          editButton.title = '编辑';
          
          const copyButton = document.createElement('button');
          copyButton.className = 'notes-action-btn copy';
          copyButton.innerHTML = '⎘';
          copyButton.title = '复制';
          
          const deleteButton = document.createElement('button');
          deleteButton.className = 'notes-action-btn delete';
          deleteButton.innerHTML = '×';
          deleteButton.title = '删除';
          
          actions.appendChild(editButton);
          actions.appendChild(copyButton);
          actions.appendChild(deleteButton);
          
          // 编辑按钮事件
          editButton.addEventListener('click', (e) => {
            e.stopPropagation();
            item.classList.add('editing');
            
            const input = document.createElement('textarea');
            input.className = 'notes-edit-input';
            input.value = note.content;
            
            const editActions = document.createElement('div');
            editActions.className = 'notes-edit-actions';
            
            const saveButton = document.createElement('button');
            saveButton.className = 'notes-edit-save';
            saveButton.textContent = '保存';
            
            const cancelButton = document.createElement('button');
            cancelButton.className = 'notes-edit-cancel';
            cancelButton.textContent = '取消';
            
            editActions.appendChild(saveButton);
            editActions.appendChild(cancelButton);
            
            content.style.display = 'none';
            actions.style.display = 'none';
            
            item.insertBefore(input, content);
            item.appendChild(editActions);
            
            input.focus();
            
            const handleSave = async () => {
              const newContent = input.value.trim();
              if (newContent && newContent !== note.content) {
                note.content = newContent;
                text.textContent = newContent;
                try {
                  await updateNote(note.id, { content: newContent });
                  noteUtils.showNotification('更新成功');
                } catch (error) {
                  noteUtils.showNotification('更新失败', true);
                }
              }
              exitEditMode();
            };

            const exitEditMode = () => {
              item.classList.remove('editing');
              content.style.display = '';
              input.remove();
              actions.style.display = '';
              editActions.remove();
            };
            
            saveButton.addEventListener('click', handleSave);
            cancelButton.addEventListener('click', exitEditMode);
            
            input.addEventListener('keydown', (e) => {
              if (e.key === 'Enter' && (e.ctrlKey || e.metaKey || e.shiftKey)) {
                e.preventDefault();
                handleSave();
              } else if (e.key === 'Escape') {
                exitEditMode();
              }
            });
          });
          
          copyButton.addEventListener('click', (e) => {
            e.stopPropagation();
            navigator.clipboard.writeText(note.content)
              .then(() => noteUtils.showNotification('已复制到剪贴板'))
              .catch(() => noteUtils.showNotification('复制失败', true));
          });
          
          deleteButton.addEventListener('click', async (e) => {
            e.stopPropagation();
            try {
              await deleteNote(note.id);
              item.classList.add('deleting');
              setTimeout(() => {
                item.remove();
                // 更新笔记数量
                const count = notesContainer.querySelectorAll('.notes-item').length;
                if (count === 0) {
                  groupContainer.remove();
                  if (historyList.children.length === 0) {
                    historyList.innerHTML = '<div class="notes-empty">暂无笔记</div>';
                  }
                } else {
                  groupContainer.querySelector('.notes-group-count').textContent = `${count}条笔记`;
                }
              }, 300);
              noteUtils.showNotification('笔记已删除');
            } catch (error) {
              noteUtils.showNotification('删除失败', true);
            }
          });

          item.appendChild(content);
          item.appendChild(actions);
          notesContainer.appendChild(item);
        });
        
        groupContainer.appendChild(groupHeader);
        groupContainer.appendChild(notesContainer);
        historyList.appendChild(groupContainer);
      });
    }
  } catch (error) {
    console.error('加载笔记失败:', error);
    historyList.innerHTML = '<div class="notes-error">加载失败</div>';
  }
  
  historySection.appendChild(historyTitle);
  historySection.appendChild(searchSection);
  historySection.appendChild(historyList);
  
  // 组装界面
  contentWrapper.appendChild(inputSection);
  contentWrapper.appendChild(historySection);
  
  container.appendChild(header);
  container.appendChild(contentWrapper);
  
  // 添加事件监听器
  const handleSave = async () => {
    const noteContent = textarea.value.trim();
    if (noteContent) {
      try {
        const id = await addNote(noteContent);
        noteUtils.showNotification('笔记已保存');
        
        const note = {
          id,
          content: noteContent,
          url: window.location.href,
          pageTitle: document.title,
          createdAt: new Date().toISOString()
        };

        // 查找当前页面的笔记组
        let groupContainer = Array.from(historyList.children).find(el => 
          el.classList.contains('notes-group') && 
          el.querySelector('.notes-group-title')?.getAttribute('href') === note.url
        );

        // 如果找不到当前页面的组，创建新的组
        if (!groupContainer) {
          const emptyNotice = historyList.querySelector('.notes-empty');
          if (emptyNotice) {
            emptyNotice.remove();
          }

          groupContainer = document.createElement('div');
          groupContainer.className = 'notes-group';
          
          const groupHeader = document.createElement('div');
          groupHeader.className = 'notes-group-header';
          groupHeader.innerHTML = `
            <a href="${note.url}" target="_blank" class="notes-group-title">${note.pageTitle}</a>
            <span class="notes-group-count">1条笔记</span>
          `;
          
          const notesContainer = document.createElement('div');
          notesContainer.className = 'notes-group-notes';
          
          groupContainer.appendChild(groupHeader);
          groupContainer.appendChild(notesContainer);
          
          // 添加到列表顶部
          historyList.insertBefore(groupContainer, historyList.firstChild);
        }

        // 创建新笔记项
        const item = document.createElement('div');
        item.className = 'notes-item new';
        
        const content = document.createElement('div');
        content.className = 'notes-item-content';
        
        const text = document.createElement('div');
        text.className = 'notes-item-text';
        text.textContent = note.content;
        
        const meta = document.createElement('div');
        meta.className = 'notes-item-meta';
        meta.innerHTML = `<span>${new Date().toLocaleString()}</span>`;
        
        content.appendChild(text);
        content.appendChild(meta);
        
        const actions = document.createElement('div');
        actions.className = 'notes-item-actions';
        
        const editButton = document.createElement('button');
        editButton.className = 'notes-action-btn edit';
        editButton.innerHTML = '✎';
        editButton.title = '编辑';
        
        const copyButton = document.createElement('button');
        copyButton.className = 'notes-action-btn copy';
        copyButton.innerHTML = '⎘';
        copyButton.title = '复制';
        
        const deleteButton = document.createElement('button');
        deleteButton.className = 'notes-action-btn delete';
        deleteButton.innerHTML = '×';
        deleteButton.title = '删除';
        
        actions.appendChild(editButton);
        actions.appendChild(copyButton);
        actions.appendChild(deleteButton);
        
        // 编辑按钮事件
        editButton.addEventListener('click', (e) => {
          e.stopPropagation();
          item.classList.add('editing');
          
          const input = document.createElement('textarea');
          input.className = 'notes-edit-input';
          input.value = note.content;
          
          const editActions = document.createElement('div');
          editActions.className = 'notes-edit-actions';
          
          const saveButton = document.createElement('button');
          saveButton.className = 'notes-edit-save';
          saveButton.textContent = '保存';
          
          const cancelButton = document.createElement('button');
          cancelButton.className = 'notes-edit-cancel';
          cancelButton.textContent = '取消';
          
          editActions.appendChild(saveButton);
          editActions.appendChild(cancelButton);
          
          content.style.display = 'none';
          actions.style.display = 'none';
          
          item.insertBefore(input, content);
          item.appendChild(editActions);
          
          input.focus();
          
          const handleSave = async () => {
            const newContent = input.value.trim();
            if (newContent && newContent !== note.content) {
              note.content = newContent;
              text.textContent = newContent;
              try {
                await updateNote(note.id, { content: newContent });
                noteUtils.showNotification('更新成功');
              } catch (error) {
                noteUtils.showNotification('更新失败', true);
              }
            }
            exitEditMode();
          };

          const exitEditMode = () => {
            item.classList.remove('editing');
            content.style.display = '';
            input.remove();
            actions.style.display = '';
            editActions.remove();
          };
          
          saveButton.addEventListener('click', handleSave);
          cancelButton.addEventListener('click', exitEditMode);
          
          input.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && (e.ctrlKey || e.metaKey || e.shiftKey)) {
              e.preventDefault();
              handleSave();
            } else if (e.key === 'Escape') {
              exitEditMode();
            }
          });
        });
        
        copyButton.addEventListener('click', (e) => {
          e.stopPropagation();
          navigator.clipboard.writeText(note.content)
            .then(() => noteUtils.showNotification('已复制到剪贴板'))
            .catch(() => noteUtils.showNotification('复制失败', true));
        });
        
        deleteButton.addEventListener('click', async (e) => {
          e.stopPropagation();
          try {
            await deleteNote(note.id);
            item.classList.add('deleting');
            setTimeout(() => {
              item.remove();
              // 更新笔记数量
              const count = notesContainer.querySelectorAll('.notes-item').length;
              if (count === 0) {
                groupContainer.remove();
                if (historyList.children.length === 0) {
                  historyList.innerHTML = '<div class="notes-empty">暂无笔记</div>';
                }
              } else {
                groupContainer.querySelector('.notes-group-count').textContent = `${count}条笔记`;
              }
            }, 300);
            noteUtils.showNotification('笔记已删除');
          } catch (error) {
            noteUtils.showNotification('删除失败', true);
          }
        });
        
        item.appendChild(content);
        item.appendChild(actions);
        
        // 添加到组的笔记容器的顶部
        const notesContainer = groupContainer.querySelector('.notes-group-notes');
        notesContainer.insertBefore(item, notesContainer.firstChild);

        // 添加动画效果
        setTimeout(() => item.classList.remove('new'), 10);
        
        textarea.value = '';
      } catch (error) {
        console.error('保存笔记失败:', error);
        noteUtils.showNotification('保存失败', true);
      }
    }
  };
  
  saveButton.addEventListener('click', handleSave);
  cancelButton.addEventListener('click', () => container.remove());
  
  // 添加键盘事件监听
  textarea.addEventListener('keydown', (e) => {
    if (e.key === 'Enter' && (e.ctrlKey || e.metaKey || e.shiftKey)) {
      e.preventDefault();
      handleSave();
    } else if (e.key === 'Escape') {
      container.remove();
    }
  });
  
  document.body.appendChild(container);
  textarea.focus();
};

// 更新笔记
const updateNote = async (id, updates) => {
  try {
    await noteUtils.checkStorageAvailable();
    // 获取现有笔记
    const result = await chrome.storage.local.get(['notes']);
    let notes = result.notes || [];
    
    // 更新指定ID的笔记
    notes = notes.map(note => 
      note.id === id ? { ...note, ...updates } : note
    );
    
    // 保存更新后的笔记列表
    await chrome.storage.local.set({ notes });
  } catch (error) {
    console.error('更新笔记失败:', error);
    throw error;
  }
};

// 导出到全局对象
window.markAnything.noteRepository = {
    addNote,
    getAllNotes,
    deleteNote,
    showNoteEditor,
    updateNote
}